package com.payment.ktb.activity.main1;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.FileUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnLongClick;

/**
 * Created by syd on 2016/6/9.
 */
public class NocardOrderConfirmZhiFuBaoActivity extends BaseActivity {



    @BindView(R.id.tv_nocardorderconfirmzhifubao_notesname)
    TextView tv_nocardorderconfirmzhifubao_notesname;
    @BindView(R.id.tv_nocardorderconfirmzhifubao_orderno)
    TextView tv_nocardorderconfirmzhifubao_orderno;
    @BindView(R.id.tv_nocardorderconfirmzhifubao_time)
    TextView tv_nocardorderconfirmzhifubao_time;
    @BindView(R.id.tv_nocardorderconfirmzhifubao_name)
    TextView tv_nocardorderconfirmzhifubao_name;
    @BindView(R.id.tv_nocardorderconfirmzhifubao_amount)
    TextView tv_nocardorderconfirmzhifubao_amount;
    @BindView(R.id.iv_nocardorderconfirmzhifubao_qrcode)
    ImageView iv_nocardorderconfirmzhifubao_qrcode;


    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nocardorderconfirmzhifubao);
        ButterKnife.bind(this);
        initTitle("二维码信息");
        initData();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                queryOrderState();
            }
        }, 10000);

    }

    /**
     *
     */
    private void initData() {
        tv_nocardorderconfirmzhifubao_amount.setText(ConstantsPay.amount + "元");
        tv_nocardorderconfirmzhifubao_time.setText(ConstantsPay.orderTime);
        tv_nocardorderconfirmzhifubao_orderno.setText(ConstantsPay.orderNo);
        tv_nocardorderconfirmzhifubao_name.setText(SharedPreferencesUtils.getString(ConstantsPay.shopName));
        tv_nocardorderconfirmzhifubao_notesname.setText(SharedPreferencesUtils.getString(ConstantsPay.shopName));
        if (TextUtils.isEmpty(getIntent().getStringExtra("codeImgUrl"))) {
            AlertDialogUtils.showAlertDialog(mContext,"生成二维码失败，请返回上一步重新生成二维码！");
        } else {
            Picasso.with(mContext).load(getIntent().getStringExtra("codeImgUrl")).fit().into(iv_nocardorderconfirmzhifubao_qrcode);
        }
    }


    @OnLongClick({R.id.iv_nocardorderconfirmzhifubao_qrcode})
    public boolean longClickEvent(View view) {
        switch (view.getId()) {
            //保存二维码到相册
            case R.id.iv_nocardorderconfirmzhifubao_qrcode:
                showDialogPlus();
                break;
        }
        return true;
    }


    /**
     *
     */
    private void showDialogPlus() {

        final String[] stringItems = {"保存相册并跳转支付宝扫一扫"};
        final ActionSheetDialog dialog = new ActionSheetDialog(mContext, stringItems, null);
        dialog.isTitleShow(false).show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    screenShotAndToAliPay();
                dialog.dismiss();
            }
        });

    }


    /**
     * 截取当前屏幕，并跳转到支付宝
     */
    private void screenShotAndToAliPay() {

        View view = getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        if (bitmap != null) {
            FileUtils.saveImageToGallery(mContext,bitmap);
            ToastUtils.showToast("保存成功！");
            toAliPayScan();
        } else {
            ToastUtils.showToast("截取当前屏幕失败！");
        }
        view.destroyDrawingCache();
    }


    /**
     * 跳转到支付宝扫一扫
     */
    private void toAliPayScan() {
        try {
            //利用Intent打开支付宝
            //支付宝跳过开启动画打开扫码和付款码的url scheme分别是alipayqr://platformapi/startapp?saId=10000007和
            //alipayqr://platformapi/startapp?saId=20000056
            Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        } catch (Exception e) {
            //若无法正常跳转，在此进行错误处理
            Toast.makeText(mContext, "无法跳转到支付宝，请检查您是否安装了支付宝！", Toast.LENGTH_SHORT).show();
        }
    }



    /**
     * 查询订单状态
     */
    private void queryOrderState() {

        if (count < 10) {

//            progressDialogUtils.showProgress("正在查询订单状态...");
            count ++;

            //构造传输参数
            String orderNo = ConstantsPay.orderNo;
            String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
            //MD5(orderNo+KEY)
            String sign = Md5Utils.md5Hex(orderNo + SharedPreferencesUtils.getString(ConstantsUser.userKey));



            //将参数放入map中
            HashMap<String, String> map = new HashMap<String,String>();

            map.put("orderNo",orderNo);
            map.put("token",token);
            map.put("sign",sign);

            //向服务器发送请求
            HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardOrderQueryState, map, mQueue, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {

//                    progressDialogUtils.dismissProgress();

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String code = jsonObject.optString("code");
                        if (Constants.NORMAL_CODE.equals(code)) {
                            String orderStatus = jsonObject.optString("orderStatus");
                            ConstantsPay.orderTime = jsonObject.optString("orderTime");
                            if ("20".equals(orderStatus)) {
                                startActivity(NocardOrderResultSuccessActivity.class);
                            } else if ("21".equals(orderStatus)) {

                                startActivity(NocardOrderResultFailActivity.class);
                                ConstantsPay.orderReason = jsonObject.optString("orderReason");
                            } else {
                                if (count < 10) {
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            queryOrderState();
                                        }
                                    }, 10000);
                                }
                            }

                        } else {

                            AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                    }
                }

                @Override
                public void onError(VolleyError volleyError) {

//                    progressDialogUtils.dismissProgress();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
                }
            });


        }
    }

/*
    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.e("onStart");
        count = 0;
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.e("onStop");
        count = 11;
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.e("onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.e("onResume");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.e("onDestroy");
    }*/


}
